import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { Session, crc32Dom, getUUID } from '/@/utils/storage';
import { useMessageBox } from '/@/hooks/message';
import { useMessage } from '/@/hooks/message';
import qs from 'qs';
import other from './other';
import CryptoJS from 'crypto-js';
import router from '../router';

/**
 * 创建并配置一个 Axios 实例对象
 */
const service: AxiosInstance = axios.create({
	baseURL: import.meta.env.VITE_API_URL,
	paramsSerializer: {
		serialize: (params: any) => {
			return qs.stringify(params, { arrayFormat: 'repeat' });
		},
	},
});
var url: InternalAxiosRequestConfig<any>;
/**
 * Axios请求拦截器，对请求进行处理
 * 1. 序列化get请求参数
 * 2. 统一增加Authorization和TENANT-ID请求头
 * 3. 自动适配单体、微服务架构不同的URL
 * @param config  AxiosRequestConfig对象，包含请求配置信息
 */
const uuidS = getUUID.generateUUID(); // 输出类似 "04bac4ea-15a8-43cf-b113-3bb4317a29c9" 的UUID 10424D5B-6CC8-4DE9-8461-5B984A4210BD
// uuidS = '10424D5B-6CC8-4DE9-8461-5B984A4210BD'; // 输出类似 "04bac4ea-15a8-43cf-b113-3bb4317a29c9" 的UUID 10424D5B-6CC8-4DE9-8461-5B984A4210BD
const version = '1.0.0'; // 示例版本号
const versionHash = crc32Dom.crc32String(version);
const uuidHash = crc32Dom.crc32String(uuidS);
const aesKey = 'UM0jOag8CDvc1SAlA0UoBG7D7BdK96XO';
const Iv = versionHash + uuidHash;
const CryptoJSkey = CryptoJS.enc.Utf8.parse(aesKey);
const CryptoJSiv = CryptoJS.enc.Utf8.parse(Iv);
var dataJson;

service.interceptors.request.use(
	(config) => {
		url = config;
		console.log(config.data);
		if (config.data != undefined) {
			let base64Date = config.data;
			dataJson = JSON.stringify(base64Date);
			const Uin8Array = other.encryptUin8Array(dataJson, CryptoJSkey, CryptoJSiv); //加密
			config.data = Uin8Array;
		} else {
			var configJson = { config: '200' };
			const Uin8Array = other.encryptUin8Array(JSON.stringify(configJson), CryptoJSkey, CryptoJSiv); //加密
			config.data = Uin8Array;
		}
		config.headers = config.headers || {};
		// 统一设置公共 headers
		config.headers['uuid'] = uuidS;
		config.headers['Content-Type'] = 'text/plain';

		Object.assign(config.headers, commonHeaders);

		const token = Session.getToken();
		console.log(token);
		if (token && !config.headers?.skipToken) {
			// config.headers![CommonHeaderEnum.AUTHORIZATION] = `Bearer ${token}`;
			config.headers![CommonHeaderEnum.AUTHORIZATION] = `Bearer ${token}`;
		}

		// 请求报文加密
		if (config.headers![CommonHeaderEnum.ENC_FLAG]) {
			const enc = other.encryption(JSON.stringify(config.data), import.meta.env.VITE_PWD_ENC_KEY);
			config.data = {
				encryption: enc,
			};
		}

		// 自动适配单体和微服务架构不同的URL
		config.url = other.adaptationUrl(config.url);

		// 处理完毕，返回config对象
		return config;
	},
	(error) => {
		// 对请求错误进行处理
		return Promise.reject(error);
	}
);

/**
 * 响应拦截器处理函数
 * @param response 响应结果
 * @returns 如果响应成功，则返回响应的data属性；否则，抛出错误或者执行其他操作
 */
const handleResponse = (response: AxiosResponse<any>) => {
	// other.convertUin8Array(response);
	if (response.data.status === 200) {
		throw response.data;
	}

	// 针对密文返回解密

	// const originData = JSON.parse(other.decryption(response.data, import.meta.env.VITE_PWD_ENC_KEY));
	if (response.data instanceof Blob) {
		//判断Blob 直接返回
		return response.data;
	} else {
		const originData = other.convertUin8Array(response.data, CryptoJSkey, CryptoJSiv);
		response.data = originData;
		console.log('解析》》》》》》》》》', url.url, originData, '??????????????????????');
		if (response.data.code === 2) {
			useMessageBox()
				.confirm('令牌状态已过期，请点击重新登录')
				.then(() => {
					Session.clear(); // 清除浏览器全部临时缓存
					// window.location.href = '/login'; // 去登录页
					router.push('/login'); // 跳转到日志管理页面
					return;
				});
			setTimeout(function () {
				Session.clear(); // 清除浏览器全部临时缓存
				router.push('/login'); // 跳转到日志管理页面
			}, 1000);
		}
		if (response.data.code === 1 || response.data.code === -1) {
			useMessage().error(response.data.msg);
		}
		if (response.data.code === 0) {
			return response.data;
		}
	}
};

/**
 * 添加 Axios 的响应拦截器，用于全局响应结果处理
 */
service.interceptors.response.use(handleResponse, (error) => {
	const status = Number(error.response.status) || 2;

	console.log(error.response);
	if (status === 424) {
		useMessageBox()
			.confirm('令牌状态已过期，请点击重新登录')
			.then(() => {
				Session.clear(); // 清除浏览器全部临时缓存
				router.push('/login'); // 跳转到日志管理页面
				return;
			});
		setTimeout(function () {
			Session.clear(); // 清除浏览器全部临时缓存
			router.push('/login'); // 跳转到日志管理页面
		}, 1000);
	}
	if (status === 500) {
		useMessage().error(error.response.statusText);
	}

	return Promise.reject(error.response.data || error.response.msg);
});

// 常用header
export enum CommonHeaderEnum {
	'TENANT_ID' = 'TENANT-ID',
	'ENC_FLAG' = 'Enc-Flag',
	'AUTHORIZATION' = 'Authorization',
	'source' = 'source',
	'version' = 'version',
	'udId' = 'udId',
}

//公共
const commonHeaders: Record<string, string> = {
	[CommonHeaderEnum.source]: 'ZZDNEWS_ADMIN',
	[CommonHeaderEnum.version]: '1.0.0',
	[CommonHeaderEnum.udId]: '',
};

// 导出 axios 实例
export default service;
